package com.design.movieticket.login.service;

import com.design.movieticket.common.base.constant.Result;

import com.design.movieticket.entity.User;
import com.design.movieticket.login.entity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
@SuppressWarnings("all")
public class LogoutService {

    @Resource
    RedisService redisService;

    public Result logout(){
        /**
         * 获取SecurityContext对象中的用户id
         * 当用户发起退出登录的请求时经过JwtAuthenticationTokenFilter过滤器认证时
         * 会将authentication(UsernamePasswordAuthenticationToken)对象存入到SecurityContext中
         * 这里可以通过authentication.getPrincipal()直接获取到User对象
         */
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        log.info("Principal" + String.valueOf(usernamePasswordAuthenticationToken.getPrincipal()));
        LoginUser loginUser = new LoginUser();
        loginUser.setUser((User) usernamePasswordAuthenticationToken.getPrincipal());
        String id = loginUser.getUser().getId().toString();

        //删除redis中的值
        redisService.del("login" + id);
        return new Result(true,"注销成功");
    }
}
